package com.meihua.shellapp.base;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.support.multidex.MultiDex;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;
import com.lzy.okgo.model.HttpHeaders;
import com.lzy.okgo.model.HttpParams;
import com.meihua.shellapp.databean.UserDataBean;
import com.meihua.shellapp.utils.ToastUtils;
import com.meihua.shellapp.utils.Utils;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.BuildConfig;
import com.orhanobut.logger.Logger;
import com.umeng.socialize.Config;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import okhttp3.OkHttpClient;

/**
 * 作者：lc on 2017/9/26.
 * 邮箱：lc0607live@163.com
 */

public class MyApplication extends Application {

    private static MyApplication application;
    private String private_key = "meihua-insurance";
    private String request_time;
    public UserDataBean bean;
    private List<Activity> activitiesAll = new ArrayList<>();

    public int[] mWh = new int[2];
    public long time;

    public static MyApplication getInstance() {
        return application;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Config.DEBUG = true;
        UMShareAPI.get(this);
        Logger.addLogAdapter(new AndroidLogAdapter() {
            @Override public boolean isLoggable(int priority, String tag) {
                return BuildConfig.DEBUG;
            }
        });
        application = this;
        Utils.init(application);
        initOKGo();
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    {

//        PlatformConfig.setWeixin("wx967daebe835fbeac", "5bb696d9ccd75a38c8a0bfe0675559b3");
        PlatformConfig.setQQZone("1106413005", "CiLifzWeAFnqTa4a");
//        PlatformConfig.setSinaWeibo("3921700954", "04b48b094faeb16683c32669824ebdad", "http://sns.whalecloud.com");
    }

    /*初始化okgo*/
    private void initOKGo() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo");
        //log打印级别，决定了log显示的详细程度
        loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);
        //log颜色级别，决定了log在控制台显示的颜色
        loggingInterceptor.setColorLevel(Level.INFO);
        builder.addInterceptor(loggingInterceptor);
        //全局的读取超时时间
        builder.readTimeout(15000, TimeUnit.MILLISECONDS);
        //全局的写入超时时间
        builder.writeTimeout(15000, TimeUnit.MILLISECONDS);
        //全局的连接超时时间
        builder.connectTimeout(15000, TimeUnit.MILLISECONDS);
        HttpHeaders headers = new HttpHeaders();
//        headers.put("commonHeaderKey1", "commonHeaderValue1");    //header不支持中文，不允许有特殊字符
        request_time = System.currentTimeMillis() + "";
        HttpParams params = new HttpParams();
        params.put("key", MD5(MD5(request_time) + private_key));
        params.put("request_time", request_time);

//        params.put("commonParamsKey1", "commonParamsValue1");     //param支持中文,直接传,不要自己编码
        OkGo.getInstance().init(this)                       //必须调用初始化
                .setOkHttpClient(builder.build())               //建议设置OkHttpClient，不设置将使用默认的
                .setCacheMode(CacheMode.REQUEST_FAILED_READ_CACHE)               //全局统一缓存模式，默认不使用缓存，可以不传
                .setCacheTime(60 * 60 * 24 * 28)   //全局统一缓存时间，4周
                .setRetryCount(3)                               //全局统一超时重连次数，默认为三次，那么最差的情况会请求4次(一次原始请求，三次重连请求)，不需要可以设置为0
                .addCommonHeaders(headers)                      //全局公共头
                .addCommonParams(params);                       //全局公共参数
    }

    public int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen",
                "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    public String getUserId() {
        return bean == null ? "" : bean.getM_number();
    }

    public String getMId() {
        return bean == null ? "" : bean.getMid();
    }

    /**
     * 处理后台返回json异常
     *
     * @param clazz 要转换的类
     * @param json  要转换的json
     * @return 如果返回null，说明数据结构异常，不用做任何操作
     */
    public <T> T getBeanForJson(Class clazz, String json) {
        try {
            T t = (T) new Gson().fromJson(json, clazz);
            return t;
        } catch (Exception e) {
            try {
                BaseBean b = new Gson().fromJson(json, BaseBean.class);
                ToastUtils.getInstance().showToast(b.getMsg() + "---数据格式返回错误");
                return null;
            } catch (Exception e1) {
                e1.printStackTrace();
                ToastUtils.getInstance().showToast("基本数据返回格式不对，可能后台报错");
                return null;
            }
        }

    }


    /**
     * md5加密
     *
     * @param sourceStr 加密的字符串
     * @return
     */
    public String MD5(String sourceStr) {
        String result = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(sourceStr.getBytes());
            byte b[] = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
//            result = buf.toString().substring(8, 24);//16位
            result = buf.toString();//32位
        } catch (NoSuchAlgorithmException e) {
            System.out.println(e);
        }
        return result;
    }

    public void addActivity(Activity activity) {
        activitiesAll.add(activity);
    }

    public void edit() {
        for (Activity temp : activitiesAll) {
            temp.finish();
        }
    }
}
